package me.shurufa.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.litesuits.common.utils.MD5Util;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.StringHttpRequestCallback;
import cn.finalteam.toolsfinal.coder.MD5Coder;
import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.activities.NewLoginActivity;
import me.shurufa.activities.NewMainActivity;
import me.shurufa.activities.ResetPasswordGetCodeActivity;
import me.shurufa.activities.ThirdPartyActivity;
import me.shurufa.db.PersistenceUtils;
import me.shurufa.model.LoginResponse;
import me.shurufa.net.API;
import me.shurufa.net.RequestParams;
import me.shurufa.net.RequestServerTask;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.LoginResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.NetworkUtils;
import me.shurufa.utils.ShareConstants;
import me.shurufa.utils.Utils;

/**
 * 登录Fragment
 *
 * @FileName: me.shurufa.fragments.LoginFragment.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-15 10:02
 */
public class NewLoginFragment extends BaseFragment implements View.OnClickListener {
    @Bind(R.id.mobile_edit)
    EditText mobileEdit;
    @Bind(R.id.password_edit)
    EditText passwordEdit;
    @Bind(R.id.log_in_button)
    Button logInButton;
    @Bind(R.id.read_text)
    TextView readText;
    @Bind(R.id.go_register)
    LinearLayout goRegister;
    @Bind(R.id.tv_forget_pwd)
    TextView mForgetPwdTv;
    @Bind(R.id.iv_enter_not_login)
    LinearLayout iv_enter_not_login;

    @Bind(R.id.iv_qq)
    ImageView iv_qq;
    @Bind(R.id.iv_weibo)
    ImageView iv_weibo;
    @Bind(R.id.iv_weixin)
    ImageView iv_weixin;

    private UMShareAPI mShareAPI;
    private int fromWhere;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_new_login, container, false);
        ButterKnife.bind(this, view);
        mShareAPI = UMShareAPI.get(getActivity());
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        fromWhere = ((NewLoginActivity) getActivity()).fromWhere;
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        if (Global.DEBUG) {
            mobileEdit.setText("15600195562");
            passwordEdit.setText("aaaaaaaa");
            Utils.moveCursorToLast(mobileEdit);
        }
        logInButton.setOnClickListener(this);
        readText.setOnClickListener(this);
        goRegister.setOnClickListener(this);
        mForgetPwdTv.setOnClickListener(this);
        iv_enter_not_login.setOnClickListener(this);

        iv_qq.setOnClickListener(this);
        iv_weibo.setOnClickListener(this);
        iv_weixin.setOnClickListener(this);
    }

    private boolean isInputValid() {
        return !TextUtils.isEmpty(mobileEdit.getText().toString()) && !TextUtils
                .isEmpty(passwordEdit.getText().toString());
    }

    @Override
    public void onClick(View v) {
        SHARE_MEDIA platform = null;
        switch (v.getId()) {
            case R.id.log_in_button:
                if (isInputValid()) {
                    login(Constants.LOGIN_TYPE_LOCAL, mobileEdit.getText().toString(), passwordEdit.getText().toString(), null, null, null);
                }
                break;
            case R.id.go_register:
            case R.id.read_text:
                EventBus.getDefault().post(new Intent(Constants.ACTION_LOGIN_SWITCH));
                break;
            case R.id.tv_forget_pwd:
                startActivity(new Intent(getActivity(), ResetPasswordGetCodeActivity.class));
                break;
            case R.id.iv_enter_not_login:

                // 删除登录信息
                // Utils.clearLogin();
                PersistenceUtils.logout();
                Intent intent = new Intent(getActivity(), NewMainActivity.class);
                startActivity(intent);
                getActivity().finish();
                break;


            case R.id.iv_qq:
                platform = SHARE_MEDIA.QQ;
                if (mShareAPI.isInstall(getActivity(), platform)) {
                    mShareAPI.doOauthVerify(getActivity(), platform, umAuthListener);
                } else {
                    Utils.showToast("请安装QQ客户端");
                }
                break;
            case R.id.iv_weibo:
                platform = SHARE_MEDIA.SINA;
                mShareAPI.doOauthVerify(getActivity(), platform, umAuthListener);
                break;
            case R.id.iv_weixin:
                platform = SHARE_MEDIA.WEIXIN;
                mShareAPI.doOauthVerify(getActivity(), platform, umAuthListener);
                break;
        }
    }

    private void login(final String loginType, String mobile, String pwd, final String openid, final String accessToken, final String unionid) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("login_type", loginType);
        if (Constants.LOGIN_TYPE_LOCAL.equalsIgnoreCase(loginType)) {
            params.addFormDataPart("mobile", mobile);
            params.addFormDataPart("password", MD5Coder.getMD5Code(pwd));
        } else {
            params.addFormDataPart("openid", openid);
            params.addFormDataPart("token", accessToken);
            params.addFormDataPart("unionid", unionid);
        }
        HttpRequest.post(API.LOGIN, params, new HttpCallback<LoginResp>(getActivity()) {
            @Override
            public void onRespSuccess(LoginResp result) {
                try {
                    // 第三方账号未绑定
                    if (Constants.ACCOUNT_UNBOUND == result.code) {
                        Intent in = new Intent(getActivity(), ThirdPartyActivity.class);
                        ThirdPartyActivity.initArguments(in, loginType, openid, accessToken, unionid);
                        startActivity(in);
                    }

                    // 已绑定过的 保存新的用户信息
                    else {
                        if (result.data != null) {
                            PersistenceUtils.setUser(result.data);
                            handleStartActivity();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(LoginResp result) {
            }
        });

    }

    private void handleStartActivity() {
        if (fromWhere == Constants.TYPE_FROM_MAIN_TO_LOGIN) {
            Intent in = new Intent(Constants.EVENT_SHOW_USER_AVATAR);
            EventBus.getDefault().post(in);
        }
        Intent intent = new Intent(getActivity(), NewMainActivity.class);
        startActivity(intent);
        getActivity().finish();
    }

    /**
     * auth callback interface
     **/
    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            try {
                Utils.showToast("授权成功");
                if (Constants.LOGIN_TYPE_QQ.equalsIgnoreCase(platform.name())) {
                    login(Constants.LOGIN_TYPE_QQ, null, null, data.get("openid"), data.get("access_token"), null);
                    return;
                }

                if ("SINA".equalsIgnoreCase(platform.name())) {
                    login(Constants.LOGIN_TYPE_WEIBO, null, null, data.get("uid"), data.get("access_token"), null);
                    return;
                }
            } catch (Exception e) {
                Utils.showToast(getString(R.string.shouquan_failure));
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Utils.showToast("授权失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Utils.showToast("取消授权");
        }
    };

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (Constants.ACTION_AUTH_WEIXIN.equals(intent.getAction())) {
            String wxCode = intent.getStringExtra("code");
            // 根据code去请求openid 和 accessToken
            reqWeixinToken(wxCode);
        }
    }

    /**
     * 第三方登录 请求微信的openid和accessToken
     *
     * @param wxCode
     */
    private void reqWeixinToken(String wxCode) {
        if (!NetworkUtils.isNetAvailable(getActivity())) {
            Utils.showToast(R.string.network_error);
            return;
        }

        cn.finalteam.okhttpfinal.RequestParams params = new cn.finalteam.okhttpfinal.RequestParams();
        params.addFormDataPart("appid", ShareConstants.WX_ID);
        params.addFormDataPart("secret", ShareConstants.WX_SECRECT);
        params.addFormDataPart("code", wxCode);
        params.addFormDataPart("grant_type", "authorization_code");

        HttpRequest.post("https://api.weixin.qq.com/sns/oauth2/access_token", params, new StringHttpRequestCallback() {
            @Override
            protected void onSuccess(String response) {
                super.onSuccess(response);
                try {
                    JSONObject json = new JSONObject(response);
                    String openid = json.optString("openid");
                    String accessToken = json.optString("access_token");
                    String unionid = json.optString("unionid");

                    if (TextUtils.isEmpty(openid) || TextUtils.isEmpty(accessToken) || TextUtils.isEmpty(unionid)) {
                        Utils.showToast(getString(R.string.shouquan_failure));
                        return;
                    }

                    if (Global.DEBUG) {
                        Utils.showToast("openid: " + openid + "\naccessToken: " + accessToken);
                    }
                    login(Constants.LOGIN_TYPE_WEIXIN, null, null, openid, accessToken, unionid);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }
}
